package info.ask4research.dao.core.impl;

import info.ask4research.dao.core.AbstractDao;

import java.util.List;

import javax.naming.NamingException;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;


public abstract class AbstractDaoImpl<T> implements AbstractDao<T>{

	protected Class<T> clazz;
	
	/**
	 * Constructor that takes in a class to see which type of entity to persist
	 * 
	 * @param clazz
	 *            the class type you'd like to persist
	 * @throws NamingException 
	 */
	public AbstractDaoImpl(Class<T> clazz) {
		this.clazz = clazz;
	}
	
	private HibernateTemplate hibernateTemplate;

	@Autowired
	public void hibernateTemplate(SessionFactory sessionFactory) {
		hibernateTemplate = new HibernateTemplate(sessionFactory);
	}

	@Override
	public T get(int id) {
		return hibernateTemplate.get(clazz, id);
	}

	@Override
	public List<T> getAll() {
		return hibernateTemplate.loadAll(clazz);
	}

	@Override
	public boolean exists(int id) {
		T entity = get(id);
		return entity != null;
	}

	@Override
	public T save(T object) {
		return hibernateTemplate.merge(object);
	}
	
	@Override
	public void saveOrUpdate(T object) {
		hibernateTemplate.saveOrUpdate(object);
	}

	@Override
	public void saveAll(List<T> elements) {
		hibernateTemplate.saveOrUpdateAll(elements);
	}

	@Override
	public void removeAll() {
		hibernateTemplate.deleteAll(getAll());
	}

	@Override
	public void removeAll(List<T> elements) {
		hibernateTemplate.deleteAll(elements);		
	}

	@Override
	public void remove(int id) {
		hibernateTemplate.delete(get(id));
	}

	@Override
	public void remove(T entity) {
		hibernateTemplate.delete(entity);
	}

	@Override
	public boolean contains(T object) {
		return hibernateTemplate.contains(object);
	}

}
